#!/usr/bin/env python
# -*- coding:utf-8 -*-
from config import config,interceptConfig
from utils.txthandle import writeTxt
from utils.timehandle import get_multipart_fn_timestamp
from utils.mitmSqlEx import mitmex_insert_data
import json,os
PATH = os.path.abspath(os.path.dirname(__file__))
MPFILEPATH = PATH + os.sep + "multipartfile"

def req_multipart_write_txt(func):
    def wrapper(*args,**kwargs):
        conf = config()
        filters = conf.get_filters()
        thisFlow = object()
        thisObj = object()
        argsList = []
        insDict = {
            'method':'',
            'url':'',
            'headers':'',
            'params':'',
            'create_time':'',
            'system_name':'',
            'is_request':0,
            'is_response':0
        }
        for i,v in enumerate(args):
            argsList.append(v)
        for v in argsList:
            if hasattr(v,"request"):
                if hasattr(v.request,"headers"):
                    thisFlow = v
            if hasattr(v,"my_tools_byte_to_str"):
                thisObj = v
        if thisFlow.request.pretty_host in filters:
            method  = thisObj.my_tools_byte_to_str(thisFlow.request.data.method)
            headers = thisFlow.request.headers
            url = thisFlow.request.pretty_url
            headersDict = {}
            paramsDict = {}
            for name, value in headers.items():
                headersDict[name] = value 
            if method != '':
                if method == 'POST' or method == "PUT":
                    if 'Content-Type' in headersDict.keys():
                        if headersDict['Content-Type'].find('multipart') >= 0:
                            if isinstance(thisFlow.request.data.content,bytes):
                                for name,value in thisFlow.request.multipart_form.items():
                                    paramsDict[str(name,encoding="utf-8")] = value
                                if paramsDict:
                                    fname = "m" + get_multipart_fn_timestamp() + ".txt"
                                    fpath = MPFILEPATH + os.sep + fname
                                    writeTxt(fpath,str(paramsDict))
                                    insDict['method'] = method
                                    insDict['url'] = url
                                    insDict['headers'] = str(headersDict)
                                    insDict['params'] = fname
                                    insDict['system_name'] = thisFlow.request.pretty_host
                                    insDict['create_time'] = thisObj.my_tools_get_timestamp_str()
                                    insDict['is_request'] = 1
                                    insDict['is_response'] = 0
                                    mitmex_insert_data(insDict)
        return func(*args,**kwargs)
    return wrapper

def intercept_req_multipart_extend(func):
    def wrapper(*args,**kwargs):
        argsList = []
        thisFlow = object()
        thisObj = object()
        for i,v in enumerate(args):
            argsList.append(v)
        for v in argsList:
            if hasattr(v,"request"):
                if hasattr(v.request,"headers"):
                    thisFlow = v
            if hasattr(v,"my_tools_byte_to_str"):
                thisObj = v
        if hasattr(thisFlow.request,"headers") and \
            hasattr(thisObj,"my_tools_byte_to_str"):
            fheaders = thisFlow.request.headers
            method  = thisObj.my_tools_byte_to_str(thisFlow.request.data.method)
            currentUrl = thisFlow.request.pretty_url
            conf = config()
            iconf = interceptConfig()
            urls = conf.get_intercept_url()
            flag = conf.get_intercept_req()
            headersDict = {}
            for name, value in fheaders.items():
                headersDict[name] = value
            if flag and urls:
                for url in urls:
                    if url == currentUrl:
                        req = iconf.get_intercept_url_req(url)
                        if req:
                            params = req['params']
                            if method == 'POST' or method == "PUT":
                                if 'Content-Type' in headersDict.keys():
                                    if headersDict['Content-Type'].find('multipart') >= 0:
                                        if params != "none":
                                            if params.find("#") > 0:
                                                mparams = params.split("#")
                                                for m in mparams:
                                                    if m.find("_") > 0:
                                                        v,s = m.split("_")
                                                        if s == "del":
                                                            params = thisFlow.request.multipart_form
                                                            for k in params.keys():
                                                                if thisFlow.request.multipart_form[k] == bytes(v,encoding="utf-8"):
                                                                    thisFlow.request.multipart_form[k] = b''
                                                        else:
                                                            params = thisFlow.request.multipart_form
                                                            for k in params.keys():
                                                                if thisFlow.request.multipart_form[k] == bytes(v,encoding="utf-8"):
                                                                    thisFlow.request.multipart_form[k] = bytes(s,encoding="utf-8")
                                            elif params.find("_") > 0:
                                                v,s = params.split("_")
                                                if s == "del":
                                                    params = thisFlow.request.multipart_form
                                                    for k in params.keys():
                                                        if thisFlow.request.multipart_form[k] == bytes(v,encoding="utf-8"):
                                                            thisFlow.request.multipart_form[k] = b''
                                                else:
                                                    params = thisFlow.request.multipart_form.copy()
                                                    #print(params)
                                                    for k in params.keys():
                                                        #print(k)
                                                        if params[k]==bytes(v,encoding="utf-8"):
                                                            params[k] = bytes(s,encoding="utf-8")
                                                            
                                                    #thisFlow.request.multipart_form = {}
                                                    thisFlow.request.multipart_form[b'fullName'] = b'dddd'
                                                    #print(thisFlow.request.multipart_form)
                                                    
                                                    #for v in thisFlow.request.multipart_form.values():
                                                        #print(v)
        return func(*args,**kwargs)
    return wrapper